package wec_wallet.ebo.com.activity.wallet;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bassproject.ebo.com.ebobass.activity.MyBaseActivity;
import bassproject.ebo.com.ebobass.http_utils.interfaces.IHttpPostListener;
import bassproject.ebo.com.ebobass.http_utils.utils.Ipost;
import bassproject.ebo.com.ebobass.http_utils.utils.NetState;
import bassproject.ebo.com.ebobass.utils.IToast;
import bassproject.ebo.com.ebobass.utils.I_Share;
import bassproject.ebo.com.ebobass.utils.Lg;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wec_wallet.ebo.com.R;
import wec_wallet.ebo.com.activity.capital.ChangeIntoActivity;
import wec_wallet.ebo.com.activity.capital.TurnOutActivity;
import wec_wallet.ebo.com.bean.CoinListBean;
import wec_wallet.ebo.com.bean.WalletDateBean;
import wec_wallet.ebo.com.common.Constant;
import wec_wallet.ebo.com.common.Constants;
import wec_wallet.ebo.com.util.StringUtil;
import wec_wallet.ebo.com.utils.Functions;
import wec_wallet.ebo.com.widget.SpinnerPopupWindow;

/**
 * 币种详情界面
 * Created by Administrator on 2018/3/29.
 */

public class CoinDetailsActivity extends MyBaseActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_coinDetails_coin)
    TextView tvCoinDetailsCoin;
    //    @BindView(R.id.spinner_coinDetails)
//    Spinner spinnerCoinDetails;
    @BindView(R.id.linear_coinDetails)
    LinearLayout linear_coinDetails;
    @BindView(R.id.tv_coinDetails_balance)
    TextView tvCoinDetailsBalance;
    @BindView(R.id.tv_coinDetails_money)
    TextView tvCoinDetailsMoney;
    @BindView(R.id.rela_coinDetails_into)
    RelativeLayout relaCoinDetailsInto;
    @BindView(R.id.rela_coinDetails_out)
    RelativeLayout relaCoinDetailsOut;
    @BindView(R.id.img_coinDetails_icon)
    ImageView img_icon;
    String coinName, wallet_id;
    List<WalletDateBean> coinList;
    private SpinnerPopupWindow mSpinerPopWindow;
    /**
     * 监听popupwindow取消
     */
    private PopupWindow.OnDismissListener dismissListener = new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            StringUtil.setTextImageRight(getApplicationContext(), tvCoinDetailsCoin, R
                    .drawable.img_arrow_down);
        }
    };
    /**
     * popupwindow显示的ListView的item点击事件
     */
    private AdapterView.OnItemClickListener itemClickListener = new AdapterView
            .OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            mSpinerPopWindow.dismiss();
            wallet_id = coinList.get(position).getWallet_id();
            tvCoinDetailsCoin.setText(coinList.get(position).getWallet_name());
            getData();

        }
    };
    /**
     * 显示PopupWindow
     */
    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.linear_coinDetails:
                    mSpinerPopWindow.setWidth(linear_coinDetails.getWidth());
                    mSpinerPopWindow.showAsDropDown(linear_coinDetails);
                    StringUtil.setTextImageRight(getApplicationContext(), tvCoinDetailsCoin, R
                            .drawable.img_arrow_up);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coindetail);
        ButterKnife.bind(this);
        initViews();
    }

    @Override
    public void initViews() {
        wallet_id = getIntent().getStringExtra("name");
        coinList = new ArrayList<>();

        tvTitle.setText(getIntent().getStringExtra("desc"));

    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
        getCoinName();
        mhandle.sendEmptyMessage(1);
    }

    /**
     * 获取币种列表
     */
    private void getCoinName() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", I_Share.readAccountToken());
        map.put("uid", I_Share.readAccountUserid());
        Functions.post(this, Constant.URL_COINLIST, map, new
                ListenerCoinName(), false, true);
    }

    /**
     * 根据币种获取资产
     */
    private void getData() {

        Map<String, Object> map = new HashMap<>();
        map.put("token", I_Share.readAccountToken());
        map.put("walletid", wallet_id);
        map.put("uid", I_Share.readAccountUserid());


        Functions.post(this, Constant.URL_DETAILS, map, new
                ListenerDetails(), false, true);
    }

    @OnClick({R.id.actionbar_back,
            R.id.rela_coinDetails_into,
            R.id.rela_coinDetails_out
    })
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.actionbar_back:
                finish();
                break;
            case R.id.rela_coinDetails_into:
                startActivity(new Intent(getApplicationContext(), ChangeIntoActivity.class)
                        .putExtra(Constants.WALLETID, wallet_id));
                break;
            case R.id.rela_coinDetails_out:
                startActivity(new Intent(getApplicationContext(), TurnOutActivity.class).putExtra
                        (Constants.WALLETID, wallet_id).putExtra("from",true));

                break;
        }
    }

    private List<WalletDateBean> getCoinData(String json) {
        return new Gson().fromJson(json, CoinListBean.class).getData();
    }

    private class ListenerCoinName implements IHttpPostListener {
        @Override
        public void onTimeOut() {

        }

        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            if (null != result) {
                try {

                    JSONObject resultObject = new JSONObject(result);
                    String status = resultObject.getString("error");
                    if (resultObject.has("is_auth") && resultObject.getString("is_auth").equals
                            ("0")) {
                        IToast.show(resultObject.getString("error_msg"));
                        Functions.relogin(CoinDetailsActivity.this);//登录过期
                        return;
                    }
                    if (resultObject.has("error_msg")) {
                        IToast.show(resultObject.getString("error_msg"));
                        return;
                    }
                    if (status.equals("0")) {
                        coinList = getCoinData(result);

                        mSpinerPopWindow = new SpinnerPopupWindow(getApplicationContext(), coinList,
                                itemClickListener);
                        mSpinerPopWindow.setOnDismissListener(dismissListener);
                        linear_coinDetails.setOnClickListener(clickListener);
                    }

                } catch (Exception e) {
                    // TODO: handle exception
                    Lg.d(getClass() + ",接口解析异常：\n" + e.toString());
                }
            } else {
                Lg.d("黑名单列表 result=null");

            }
        }
    }

    private class ListenerDetails implements IHttpPostListener {
        @Override
        public void onTimeOut() {

        }

        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            if (null != result) {
                try {

                    JSONObject resultObject = new JSONObject(result);
                    String status = resultObject.getString("error");
                    if (resultObject.has("is_auth") && resultObject.getString("is_auth").equals
                            ("0")) {
                        IToast.show(resultObject.getString("error_msg"));
                        Functions.relogin(CoinDetailsActivity.this);//登录过期
                        return;
                    }
                    if (resultObject.has("error_msg")) {
                        IToast.show(resultObject.getString("error_msg"));
                        return;
                    }
                    if (status.equals("0")) {
                        JSONObject date = new JSONObject(resultObject.getString("data"));
                        tvCoinDetailsBalance.setText(date.getString("num") + " WEC");
                        tvCoinDetailsMoney.setText("≈" + date.getString("cny_price") +
                                "CNY");
                        tvCoinDetailsCoin.setText(date.getString("wallet_name"));
//                        Glide.with(getApplicationContext()).load(date.getString("icon")).into
//                                (img_icon);
//                        img_icon.setImageResource(R.drawable.ic_logout);
                    }

                } catch (Exception e) {
                    // TODO: handle exception
//                    IToast.show(e.toString());
                    Lg.d(getClass() + ",接口解析异常：\n" + e.toString());
                }
            } else {
                Lg.d("黑名单列表 result=null");

            }
        }
    }

    Handler mhandle = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    int time = 5;
                    sendMessageDelayed(obtainMessage(1), time * 1000);
                    if (NetState.isNetworkAvailable(getApplicationContext())) {
                        getData();
                    }


                    break;
                case 2:
                    break;


            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mhandle.removeMessages(1);

    }

    @Override
    protected void onPause() {

        super.onPause();
        mhandle.removeMessages(1);
    }
}
